from pathlib import Path
from PyQt6.QtCore import Qt, QUrl, QSize, pyqtSignal
from PyQt6.QtGui import QFont, QColor
from PyQt6.QtWidgets import QWidget, QLabel, QHBoxLayout, QVBoxLayout
from qfluentwidgets import CaptionLabel, ElevatedCardWidget, ImageLabel, FlowLayout, FlyoutView, Flyout, PushButton, \
	FlyoutAnimationType, FlyoutViewBase, BodyLabel, PrimaryPushButton, HyperlinkLabel, VerticalSeparator, \
	PillPushButton, TransparentToolButton, setFont, FluentIcon, SimpleCardWidget, VBoxLayout, ComboBox
from qfluentwidgets.components.widgets.frameless_window import FramelessWindow
from qfluentwidgets import FluentIcon as FIF
from qfluentwidgets import BodyLabel, ImageLabel, PrimaryPushButton, TitleLabel
from PyQt6 import QtCore, QtGui, QtWidgets
import serial.tools.list_ports
from src.control.control import Control


class device():
	def __init__(self, name: str, iconPath: str, context: str, imagePath: str):
		self.name = name
		self.iconPath = iconPath
		self.context = context
		self.imagePath = imagePath
		self.control = Control


# 设备卡片组件
class DeviceCard(ElevatedCardWidget):
	deviceClicked = pyqtSignal(object)  # 自定义信号
	def __init__(self, device, parent=None):  # 传入一个device类
		super().__init__(parent)
		self.device = device
		self.iconWidget = ImageLabel(self.device.iconPath, self)
		self.label = CaptionLabel(self.device.name, self)

		self.iconWidget.scaledToHeight(68)

		self.vBoxLayout = QVBoxLayout(self)
		self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
		self.vBoxLayout.addStretch(1)
		self.vBoxLayout.addWidget(self.iconWidget, 0, Qt.AlignmentFlag.AlignCenter)
		self.vBoxLayout.addStretch(1)
		self.vBoxLayout.addWidget(self.label, 0, Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignBottom)

		self.setFixedSize(168, 176)

		self.clicked.connect(self.emit_device_clicked)

	#点击发送信号
	def emit_device_clicked(self):
		#print(f"当前设备为{self.device.name}")
		self.deviceClicked.emit(self.device)
		#print("已发送信号")


#硬件信息页面
class DeviceInfoCard(SimpleCardWidget):
	#ComListClicked = pyqtSignal(object) # 更新COM列表的信号
	def __init__(self,device, control, parent=None):
		super().__init__(parent)
		self.control = control
		self.iconLabel = ImageLabel(device.imagePath, self)
		self.iconLabel.setBorderRadius(8, 8, 8, 8)
		self.iconLabel.scaledToWidth(120)

		self.nameLabel = TitleLabel(device.name, self)
		self.connectButton = PrimaryPushButton('连接', self)
		self.companyLabel = HyperlinkLabel(
			QUrl('https://gitee.com/sumght/spectrometer-control-platform'), '设备详情', self)
		self.connectButton.setFixedWidth(160)

		self.COM_comboBox = ComboBox(self)
		self.COM_comboBox.setPlaceholderText("选择端口")
		self.COM_comboBox.setFixedWidth(160)

		#self.scoreWidget = StatisticsWidget('平均', '5.0', self)
		self.separator = VerticalSeparator(self)
		#暂时用名字进行判断
		if device.name=="Motor_1.0":
			if control.motor_conn:
				self.status_label = BodyLabel("连接状态：已连接")
				self.status_label.setTextColor("green")
			else:
				self.status_label = BodyLabel("连接状态：未连接")
				self.status_label.setTextColor(QColor(255, 0, 0))
		if device.name=="Spectrometer_1.0":
			if control.spec_conn:
				self.status_label = BodyLabel("连接状态：已连接")
				self.status_label.setTextColor("green")
			else:
				self.status_label = BodyLabel("连接状态：未连接")
				self.status_label.setTextColor(QColor(255, 0, 0))

		self.descriptionLabel = BodyLabel(
			device.context,
			self)
		self.descriptionLabel.setWordWrap(True)

		self.tagButton = PillPushButton('硬件类型', self)
		self.tagButton.setCheckable(False)
		setFont(self.tagButton, 12)
		self.tagButton.setFixedSize(80, 32)

		self.closeButton = TransparentToolButton(FluentIcon.CLOSE, self)
		self.closeButton.setFixedSize(32, 32)
		self.closeButton.setIconSize(QSize(14, 14))

		self.hBoxLayout = QHBoxLayout(self)
		self.vBoxLayout = QVBoxLayout()
		self.statusLayout = QHBoxLayout()#
		self.topLayout = QHBoxLayout()
		self.statisticsLayout = QHBoxLayout()
		self.buttonLayout = QHBoxLayout()

		self.initLayout()

		#信号连接部分
		self.COM_comboBox.clicked.connect(self.COM_comboBox_clicked)
		self.connectButton.clicked.connect(self.connectButton_clicked)

	def initLayout(self):
		self.hBoxLayout.setSpacing(30)
		self.hBoxLayout.setContentsMargins(34, 24, 24, 24)
		self.hBoxLayout.addWidget(self.iconLabel)
		self.hBoxLayout.addLayout(self.vBoxLayout)

		self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
		self.vBoxLayout.setSpacing(0)

		# name label and install button
		self.vBoxLayout.addLayout(self.topLayout)
		self.topLayout.setContentsMargins(0, 0, 0, 0)
		self.topLayout.addWidget(self.nameLabel)
		self.topLayout.addWidget(self.connectButton, 0, Qt.AlignmentFlag.AlignRight)

		# company label
		self.vBoxLayout.addSpacing(3)
		# self.vBoxLayout.addWidget(self.companyLabel)
		# self.vBoxLayout.addWidget(self.COM_comboBox)
		self.statusLayout.addWidget(self.companyLabel)
		self.statusLayout.addWidget(self.COM_comboBox,0, Qt.AlignmentFlag.AlignRight)
		self.vBoxLayout.addLayout(self.statusLayout)

		# statistics widgets
		self.vBoxLayout.addSpacing(10)
		self.vBoxLayout.addLayout(self.statisticsLayout)
		self.statisticsLayout.setContentsMargins(0, 0, 0, 0)
		self.statisticsLayout.setSpacing(10)
		self.statisticsLayout.addWidget(self.separator)
		self.statisticsLayout.addWidget(self.status_label)
		self.statisticsLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)

		# description label
		self.vBoxLayout.addSpacing(15)
		self.vBoxLayout.addWidget(self.descriptionLabel)

		# button
		self.vBoxLayout.addSpacing(12)
		self.buttonLayout.setContentsMargins(0, 0, 0, 0)
		self.vBoxLayout.addLayout(self.buttonLayout)
		self.buttonLayout.addWidget(self.tagButton, 0, Qt.AlignmentFlag.AlignLeft)
		self.buttonLayout.addWidget(self.closeButton, 0, Qt.AlignmentFlag.AlignRight)
		self.closeButton.clicked.connect(self.close)

	def list_available_ports(self):
		available_ports = [port.device for port in serial.tools.list_ports.comports()]
		if len(available_ports) == 0:
			available_ports.append("无")
		print(available_ports)
		return available_ports

	def COM_comboBox_clicked(self):
		self.COM_comboBox.clear()
		self.COM_comboBox.addItems(self.list_available_ports())
		self.COM_comboBox.setCurrentIndex(-1)

	#连接按钮点击
	def connectButton_clicked(self):
		print("连接按钮点击")
		print(self.COM_comboBox.currentText())
		try:
			if self.nameLabel.text() == "Motor_1.0":#暂时用设备名字进行判定，之后迭代为设备类型
				print("设备为电机，进行电机的端口连接")
				if self.control.motor_connect(self.COM_comboBox.currentText()):# 串口连接
				# if True:
					self.status_label.setText("成功连接")
					self.status_label.setTextColor("green")
			if self.nameLabel.text() == "Spectrometer_1.0":#暂时用设备名字进行判定，之后迭代为设备类型
				print("设备为光谱仪，进行连接")
				if self.control.spectormeter_connect():# 串口连接
				# if True:
					self.status_label.setText("成功连接")
					self.status_label.setTextColor("green")
		except:
			print("连接失败")



# 整体页面
class DeviceInterface(QWidget):
	def __init__(self, text: str, control,parent=None):
		super().__init__(parent=parent)
		self.control = control
		self.main_layout = VBoxLayout(self)  # 主要布局
		self.flowLayout = FlowLayout()

		self.resize(580, 680)
		self.flowLayout.setSpacing(6)
		self.flowLayout.setContentsMargins(30, 60, 30, 30)
		self.flowLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter)

		motor = device(
			"Motor_1.0",
			"./resources/image/motor_logo.png",
			"产品名称：12V 180kg.cm  485磁编码串行总线舵机\n产品型号：SM-1500-C001\n结构尺寸：95.5*65*85mm\n产品重量：860g ±0.2\n最高转速：0.67sec/60degree (15RPM) ",
			"resources/image/motor_img.png"
		)
		spectrometer = device(
			"Spectrometer_1.0",
			"./resources/image/spectrometer_logo.png",
			"暂无设备信息添加\n设备公司：上海如海光电科技有限公司\n上海如海光电科技有限公司创立于 2011 年，\n是一家专注于光谱核心器件、光谱工业解决方案、光学科学仪器\n以及光学附件的研发、生产、服务和销售为一体的科技型企业。",
			"resources/image/spectrometer_img.png"
		)
		motor_card = DeviceCard(motor, parent=self)
		spectrometer_card = DeviceCard(spectrometer, parent=self)

		# 添加卡片到主要布局
		self.main_layout.addLayout(self.flowLayout)

		self.flowLayout.addWidget(motor_card)
		self.flowLayout.addWidget(spectrometer_card)

		# 添加一个新的布局用于添加额外内容
		self.additional_layout = QVBoxLayout()
		self.additional_layout.setContentsMargins(30, 10, 30, 30)  # 举例设置边距
		# 在新布局中添加你想要的部件
		# label = QLabel("Additional Content")
		# self.additional_layout.addWidget(label)
		# deviceCard = DeviceInfoCard(motor) # 创建设备信息部件
		# self.additional_layout.addWidget(deviceCard)
		# info页面加在这个位置
		# 连接DeviceCard的deviceClicked信号到显示设备信息的槽函数
		motor_card.deviceClicked.connect(self.show_device_info)
		spectrometer_card.deviceClicked.connect(self.show_device_info)

		# 将新布局添加到主要布局中
		self.main_layout.addLayout(self.additional_layout)
		self.setObjectName(text.replace(' ', '-'))

	def show_device_info(self, device):
		#print(f"接受当前设备为 {device.name}")
		self.clear_device_info_layout()  # 清空设备信息布局
		# label = QLabel(device.name)
		# self.additional_layout.addWidget(label)
		deviceCard = DeviceInfoCard(control=self.control,device=device) # 创建设备信息部件
		self.additional_layout.addWidget(deviceCard)

	def clear_device_info_layout(self):
		while self.additional_layout.count() > 0:
			item = self.additional_layout.takeAt(0)
			if item:
				item.widget().deleteLater()


